package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public void saveOrUpdate(StrategyComment strategyComment) {
        if (strategyComment.getId() != null) {
            strategyCommentMapper.updateByPrimaryKey(strategyComment);
        } else {
            strategyCommentMapper.insert(strategyComment);
        }
    }

    @Override
    public void saveOrUpdate(StrategyComment comment, String[] tags) {

        if (comment.getId() != null) {
            strategyCommentMapper.updateByPrimaryKey(comment);
        } else {
            //保存用户信息
            comment.setUser(UserContext.getCurrentUser());
            strategyCommentMapper.insert(comment);
            //遍历标签并保存
            for (String name : tags) {
                Tag tag = new Tag();
                tag.setName(name);
                tagMapper.insert(tag);
                //关联标签和评论的关系
                strategyCommentMapper.insertCommentAndTagRelation(comment.getId(), tag.getId());
            }
        }
    }

    @Override
    public int selectStrategyCommentsNums(Long userId) {
        return strategyCommentMapper.selectStrategyCommentsNums(userId);
    }

    @Override
    public List<StrategyComment> listAll() {
        return strategyCommentMapper.selectAll();
    }

    @Override
    public StrategyComment get(Long id) {
        return strategyCommentMapper.selectByPrimaryKey(id);
    }


    @Override
    public PageInfo query(StrategyQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), true, false, true);
        qo.setOrderBy("s.createTime DESC");
        List<StrategyComment> list = strategyCommentMapper.queryForList(qo);
        return new PageInfo(list);
    }

}
